<?php
require_once("modules/debug.class.php");
/**
 * Cache management class
 * @author Frédéric Delorme.
 * @version 1.0 - 20091211 
 */
class Cache{
	static private $_instance = null;
	private $page;
	function __construct(){
		
	}
	function exists($page=""){
		if($page!=""){
			return file_exists(dirname($_SERVER['SCRIPT_FILENAME'])."/".$this->cacheName($page));
		}
	}
	/**
	 * Start caching: test if cache for this <code>$page</code> already generated.
	 * @param $page url of the page to be cached.
	 * @return false if page not in cache, or if already cached, return buffer content.
	 */
	function start($page=""){
		if($page!=""){
			$this->page=$page;
			if(!$this->exists($page)){
				__debug(__FILE__,__LINE__,"you have to generate buffer for [$page]");
				return false;
			}else{
				__debug(__FILE__,__LINE__,"page [$page] from cache");
				$buffer=file(dirname($_SERVER['SCRIPT_FILENAME'])."/".$this->cacheName($page),FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
				return implode('',$buffer);
			}
		}else{
			return false;
		}
	} 
	public function register($content){
		if(!$this->exists($this->page)){
			$file=fopen($this->cacheName($this->page),"w+");
			fwrite($file,$content);
			fclose($file);
			__debug(__FILE__,__LINE__,"Page [$this->page] stored in cache");
		}
	}
	
	/**
	 * End of cache generation.
	 */
	function end(){
		//TODO have to find something to write here.		
	}
	
	/**
	 * calculate file cache name for <code>$page</code>.
	 * @param $page
	 * @return unknown_type
	 */	
	function cacheName($page){
		return "cache/".str_replace(array("/","?","=","&"),array("-","-","-","_"),$page).".chd";
	}
	
	/**
	 * return the static instance of the THeme Manager.
	 * create the instance if does not already exist.
	 */
	function getInstance(){
		if(!isset(self::$_instance)){
			self::$_instance = new Cache();
		}
		return self::$_instance;
	}
	
}
?>
